<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
  <script src="../node_modules/axios/dist/axios.min.js"></script>
  <style>
    #app{
     margin-left: 200px;
    }
    a{
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div id="app">
    <h1>vue-axios插件讲解</h1>
    <div>
    <a href="javascript:void(0);" class="btn btn-primary" @click="get">get请求</a>
    <a href="javascript:void(0);" class="btn btn-primary" @click="post">post请求</a>
    <a href="javascript:void(0);" class="btn btn-primary" @click="http">http请求</a>
    </div>
    <span>{{msg}}</span>
  </div>
</body>
 <script>
   new Vue({
     el:'#app',
     data:{
        msg:''
     },
     mounted(){
        // 全局请求前拦截
        axios.interceptors.request.use(config =>{
          console.log("request init..");
          return config;
        })
       //全局请求后拦截
       axios.interceptors.response.use(response =>{
         console.log("reponse init.");
         return response;
       })
     },
     methods:{
       get(){
         axios.get('../package.json', {
           params:{
             userId:"999"
           },
           headers:{
             token:"jack"
           }
         }).then(res =>{
           this.msg = res.data;
         }).catch(error =>{
           console.log("error init"+error);
         })
       },
       post(){
         axios.post("../package.json", {
           userId: '888'
         },{
           headers:{
             token:'tom'
            },
         }).then(res =>{
           this.msg = res.data;
         }).catch(error =>{
           console.log(error);
         });
         },
       http(){
          axios({
            url:"../package.json",
            // method:"get",
            // params:{
            //   userId:"101"  //get参数设置为params
            // },
            method:"post",
            data:{
              userId:"202"
            },
            headers:{
              token:"violet"
            }
          }).then(res =>{
            this.msg = res.data;
          }).catch(error =>{
            console.log(error);
          })
       }
     }
   })
 </script>
</html>
